#include "include/Curl.hpp"
#include "include/logger.hpp"

Curl::Curl(){
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if(!curl){
        throw std::runtime_error("Failed to initialize CURL");
    }
}

Curl::~Curl(){
    if(curl){
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
}

//执行get 请求
string Curl::get(const string &url){
    return preformRequest(url,"");
}

string Curl::post(const string & url,const string & data){
    return preformRequest(url,data);
}

string Curl::preformRequest(const string & url,const string & data){
    if(!curl){
        throw std::runtime_error("CURL not initialized");
    }

    response.clear();

    curl_easy_setopt(curl,CURLOPT_URL,url.c_str());
    curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,writeCallback);
    curl_easy_setopt(curl,CURLOPT_WRITEDATA,&response);

    //设置用户代理
    curl_easy_setopt(curl,CURLOPT_USERAGENT,"SimpleCurl/1.0");

    //如果是POST请求
    if(!data.empty()){
        curl_easy_setopt(curl,CURLOPT_POST,1L);
        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,data.c_str());
        curl_easy_setopt(curl,CURLOPT_POSTFIELDSIZE,data.size());
    }


    CURLcode res = curl_easy_perform(curl);

    if(res != CURLE_OK){
        //throw std::runtime_error("CURL error: "+ std::string(curl_easy_strerror(res)) );
        LOG_ERROR(("CURL error: "+ std::string(curl_easy_strerror(res))).c_str());
    }

    return response;

}
